import { Component, OnInit, Inject, ViewChild, AfterViewChecked } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NgForm, FormControl } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatDatepickerInputEvent} from '@angular/material';
import { Moment } from 'moment';
import * as moment from 'moment';
declare var $: any;
import { Asset} from '../../models/Asset';
import { SelectionModel } from '@angular/cdk/collections';
import { map } from 'rxjs/operators';
import { environment } from '../../environments/environment';
import { DepartmentService } from '../../service/departmentService';
import { Department } from '../../models/Department';
import { UserService } from '../../service/userService';
import { AssetService } from '../../service/assetService';
import { User } from '../../models/User';
import { DepartmentaddComponent } from '../departmentadd/departmentadd';
import { UseraddComponent } from '../useradd/useradd';
import { Deliver, RepairStatusMap, RepairStatus } from '../../models/Deliver';
import { RepairService } from '../../service/repairService';
import {AssetType} from '../../models/AssetType';

@Component({
  templateUrl: './repairedit.html',
  styleUrls: ['./repairedit.css']
})
export class RepaireditComponent implements OnInit, AfterViewChecked {
  messages = {
    status: ''
  };
  RepairStatusMap = RepairStatusMap;
  RepairStatus = RepairStatus;
  selection: SelectionModel<Asset>;
  asset: Asset;
  deliver: Deliver;
  assets: Asset[];
  departments: Department[];
  users: User[];
  departmentid: number;
  page = 1;
  pageSize = 50;
  total: number;
  assetIds: any = [];
  cols = ['select', 'assetCode', 'assetName', 'assetType', 'assetDate', 'departName', 'username'];
  editRepair: Deliver;
  constructor(
    private departmentService: DepartmentService,
    private userService: UserService,
    private assetService: AssetService,
    private repairService: RepairService,
    private dialog: MatDialog,
    private route: ActivatedRoute,
    private dialogRef: MatDialogRef<RepaireditComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {repairs: Deliver}
  ) {
    this.deliver = data.repairs;
    this.deliver.sysDepartment = data.repairs.sysDepartment;
    this.deliver.sysUser = data.repairs.sysUser;
  }
  @ViewChild('repaireditForm')
  repaireditForm: NgForm;
  ngAfterViewChecked() {
    if (this.repaireditForm) {
      this.repaireditForm.valueChanges.subscribe(data => this.checkValidate());
    }
  }

  ngOnInit() {
    this.editRepair = new Deliver();
    const initialSelection = [];
    const allowMultiSelect = true;
    this.selection = new SelectionModel<Asset>(allowMultiSelect, initialSelection);
  }

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.assets.length;
    return numSelected === numRows;
  }
  allToggle() {
    this.isAllSelected() ?
      this.selection.clear() :
      this.assets.forEach(row => {this.selection.select(row);});

  }
  itemChanged(item, event) {
    item.isChecked = event.checked;
    if (item.isChecked) {
      this.assetIds.push(item.id);
    } else {
      for (let i = 0; i < this.assetIds.length; i++ ) {
        if (this.assetIds[i] === item.id) {
          this.assetIds.splice(i, 1);
        }
      }
    }

  }
  trackById(index: number, item: any) {
    return item.id;
  }
  onPageChanged(page: number) {
    this.page = page;
  }

  onSubmit() {
    this.deliver.ids = this.assetIds.join(',');
    this.checkValidate(true);
    if (this.repaireditForm.invalid) {
      // 触发mat的error
      this.repaireditForm.onSubmit(null);
      return false;
    }
    this.repairService.update(this.deliver).subscribe((res) => {
      if (res.success) {
        this.dialogRef.close(res.res);
      }
    })

  }
  checkValidate(isSubmit?: boolean) {
    const form = this.repaireditForm;

    for (const field in RepaireditComponent.ErrorMessages) {

      const control = form.controls[field];

      if (control && control.valid) {
        this.messages[field] = '';
      }
      if (control && (control.dirty || isSubmit) && !control.valid) {
        const messages = RepaireditComponent.ErrorMessages[field];
        if (control.errors) {
          this.messages[field] = messages[Object.keys(control.errors)[0]];
        }
      }
    }
  }

  static ErrorMessages = {
    status: {
      required: '维修状态不能为空'
    }
  };
}
